package com.hht.netlibs

import okhttp3.Call
import okhttp3.HttpUrl
import okhttp3.Request


/**
 * Author:chen'hu
 * Time:2024/6/18 15:14
 * Description:This is ReplaceUrlCallFactory
 */
abstract class ReplaceUrlCallFactory(delegate: Call.Factory) : CallFactoryProxy(delegate) {

    /**
     *TODO 动态添加baserUrl以下二种方式
     * @Headers("BaseUrlName:xxx") for method, or
     * method(@Header("BaseUrlName") String name) for parameter
     */
    override fun newCall(request: Request): Call {
        var mTempRequest = request
        val baseUrlName = request.header(BASE_URL_NAME)
        baseUrlName?.let {
            val newHttpUrl = getNewUrl(it, request)
            newHttpUrl?.apply {
                mTempRequest = request.newBuilder().url(this).build()
            }
        }
        return delegate.newCall(mTempRequest)
    }

    protected abstract fun getNewUrl(baserUrlName: String, request: Request): HttpUrl?

    companion object {
        private const val BASE_URL_NAME = "BaseUrlName"
    }
}